﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace DBService
{
	public partial class DlgSetRole : System.Windows.Forms.Form
	{
		public DlgSetRole(string group)
		{
			this.mGroup = group;
			this.InitializeComponent();
		}

		private void DlgSetRole_Load(object sender, EventArgs e)
		{
			foreach (DbUser item in DbUser.GetAllUsers(BimServerDB.Default))
			{
				this.cbxUsers.Items.Add(item);
			}
			if (this.cbxUsers.Items.Count > 0)
			{
				this.cbxUsers.SelectedIndex = 0;
			}
		}

		private void btnCancle_Click(object sender, EventArgs e)
		{
			base.Close();
		}

		private void btnOK_Click(object sender, EventArgs e)
		{
			if (this.cbxUsers.SelectedItem != null)
			{
				try
				{
					DbUser dbUser = (DbUser)this.cbxUsers.SelectedItem;
					List<DbRole> list = new List<DbRole>();
					foreach (object obj in ((IEnumerable)this.dgvRights.Rows))
					{
						DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
						if ((bool)dataGridViewRow.Cells["add"].Value)
						{
							list.Add(new DbRole(Convert.ToInt32(dataGridViewRow.Cells["rGUID"].Value), dataGridViewRow.Cells["rName"].Value.ToString(), dataGridViewRow.Cells["rDesc"].Value.ToString(), dbUser.Database));
						}
					}
					dbUser.UpdateRole(list, this.mGroup);
					DbUser.System.SendMessage(dbUser.Name, "管理员已重新设置你的职位。");
					MessageBox.Show("更新成功。");
				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.Message);
				}
			}
		}

		private void cbxUsers_SelectedIndexChanged(object sender, EventArgs e)
		{
			this.dgvRights.Rows.Clear();
			if (this.cbxUsers.SelectedItem != null)
			{
				try
				{
					List<DbRole> roles = ((DbUser)this.cbxUsers.SelectedItem).GetRoles();
					foreach (DbRole dbRole in DbRole.GetAllRoles(BimServerDB.Default, this.mGroup))
					{
						if (roles.Contains(dbRole))
						{
							this.dgvRights.Rows.Add(new object[]
							{
								true,
								dbRole.Name,
								dbRole.Description,
								dbRole.Id
							});
						}
						else
						{
							this.dgvRights.Rows.Add(new object[]
							{
								false,
								dbRole.Name,
								dbRole.Description,
								dbRole.Id
							});
						}
					}
				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.Message);
				}
			}
		}

		private string mGroup = "";
	}
}
